<?php
/*
 * Hooligan - A sports facilities management software
 * Copyright (C) 2009/2010 Gianluca Bargelli <g.bargelli@gmail.com>,
 * Andrea Biocco <abiocco@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project home: <http://code.google.com/hooligan>
 *
 */
require_once('../Controller/Common/Controller_Common_Config.php');
require_once('../Model/Model_Session.php');
require_once('../Model/Model_User.php');
/**
 * @brief Class with static authentication methods.
 *
 * <b>English</b>
 *
 * This class mainly implements (statical) functions for Authentication issues,
 * therefore there is no constructor;
 * It's simply a container for starting sessions and for checking credentials.
 *
 * <b>Italiano</b>
 *
 * Questa classe implementa principalmente funzioni atte all'autenticazione,
 * pertanto non vi è definito un costruttore;
 * Si tratta di un semplice contenitore di metodi per avviare sessioni e per
 * il controllo delle credenziali.
 *
 *
 *
 * @author Gianluca Bargelli
 */
class Controller_Login_Login {
    /**
     * @brief Statically starts a session.
     *
     * <b>English</b>
     *
     * Starts a session by creating a new Model_Session item;
     * It statically istantiates a new Session with
     * database connection parameters injected into the constructor.
     * Having no global scope, $session variable is lost after calling
     * the method.
     *
     *<b>Italiano</b>
     * 
     * Lancia una sessione creando un nuovo oggetto Model_Session;
     * Istanzia staticamente una nuova sessione con i parametri per la
     * connessione al database passati tramite costruttore.
     * Non avendo uno scope globale la variabile $session è persa dopo la
     * chiamata del metodo.
     */
    public static function startSession()
    {
           $session=new Model_Session(new Model_Db(new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)));
    }
    /**
     * @brief Checks if user credentials are valid.
     *
     * <b>English</b>
     *
     * Performs a database check with $_POST['username'] and $_POST['password'];
     * If POST vars are empty then it checks if there's a valid session, else
     * redirects to a login page.
     *
     * <b>Italiano</b>
     *
     * Effettua un controllo sul database con le variabili $_POST['username']
     * e $_POST['password'];
     * Se le variabili POST passate sono vuote controlla se esiste una sessione
     * ancora valida, altrimenti effettua il redirect verso una pagina di login.
     * 
     *@return BOOLEAN
     * TRUE le credenziali sono valide, FALSE altrimenti.
     *
     * @todo -Eliminare il modello User e implementare la funzione
     * userRole() come metodo statico di Controller_Login_Login
     */
    public static function checkCredentials()
    {
        //If $_POST is initialized then perform the database check with the data;
        if(array_key_exists('username', $_POST))
        {
            $username=$_POST['username'];
            $sha1Pass=sha1($_POST['password']);
            $conn=new Model_Db(new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE));
            $query=("SELECT username,pwd FROM Utente WHERE username='{$username}' AND pwd='{$sha1Pass}' LIMIT 1 ;");
            $result=$conn->eseguiQuery($query);

            if (mysqli_num_rows($result)!=0)
            {
                //Create a Model_User object (Thinking to replace it or remove it)
                $user = new Model_User($username);
                $role=$user->userRole();
                $user->setRole($role);

                //Set session array vars for future checkings
                $_SESSION['username']=$user->getUsername();
                $_SESSION['role']=$user->getRole();
                //debugging foo
                //echo ("<p>Loggato con successo!</p>");
               // Tools_CustomDebug::printItem($_SESSION);
                return true;
            }
            else
            {
                //echo"<p>Nome utente o password errati.</p>";
                return false;
            }
            //Tools_CustomDebug::printItem($_POST);
        }

        //This is executed when the session array has been initialized before (I.E. User coming back)
        else if (array_key_exists('username',$_SESSION))
        {
            return true;
            //Tools_CustomDebug::whoAmI();
        }
        //If no $_POST vars are found or no $_SESSION array redirect to login page
        else
            Template_Base::displayHeader("Login");
        {?>
        <form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST">
                <p>Username: <input type="text" name="username"/></p>
                <p>Password: <input type="password" name="password"/></p>
                <p><input type="submit" value="Ok"></p>
            </form>
         <?php
        }
    }           
}
?>
